package smashedapples.forms
{
	import com.adobe.serialization.json.JSON;
	
	import flash.events.KeyboardEvent;
	
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;
	import mx.utils.ObjectUtil;
	
	import smashedapples.google.consts.GoogleConsts;
	import smashedapples.vo.GoogleSuggestionVO;

	public class GoogleSuggestInput extends ComboBox
	{
		
		
		public function GoogleSuggestInput()
		{
			super();
			this.editable = true;
			
			this.addEventListener( KeyboardEvent.KEY_DOWN, handleKeyDownEvent );
		}
		
		private function handleKeyDownEvent( event:KeyboardEvent ):void
		{
			
			if( this.textInput.text == "" )
				return;
			
			var service:HTTPService = new HTTPService();
				service.url = GoogleConsts.SUGGEST_URL( this.textInput.text );
				service.addEventListener( ResultEvent.RESULT,  handleGetSuggestionsResult );
				service.addEventListener( FaultEvent.FAULT,  handleGetSuggestionsFault );
				service.resultFormat = "object";
				service.send();
		}
		
		private function handleGetSuggestionsFault( event:FaultEvent ):void
		{
			trace( ObjectUtil.toString( event.fault ));
		}
		
		private function handleGetSuggestionsResult( event:ResultEvent ):void
		{
			var suggestions:Array = JSON.decode( String( event.result ));
			
			if( suggestions[1] == null )
				return;
			 
			var counts:Array =  (suggestions[2] as Array )
			
			var array:Array = [];
			var i:Number = 0;
			for each( var suggestion:String in (suggestions[1] as Array ))
			{
				var vo:GoogleSuggestionVO = new GoogleSuggestionVO();
					vo.suggestion = suggestion;
					vo.count = counts[i];
				array.push( vo ); 
				i++	
			}
			
			this.dataProvider = array;
			this.rowCount = i;
			this.open();
		
		}		
		
	}
}